import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:huajianshe_app/base/AppNavigator.dart';
import 'package:huajianshe_app/base/BaseState.dart';
import 'package:huajianshe_app/common/load_image.dart';
import 'package:huajianshe_app/common/res.dart';
import 'package:huajianshe_app/network/Api.dart';
import 'package:huajianshe_app/network/response/BaseResp.dart';
import 'package:huajianshe_app/network/response/ResourceResp.dart';
import 'package:huajianshe_app/pages/circle/model/CircleModel.dart';
import 'package:huajianshe_app/pages/main/PostPage.dart';
import 'package:huajianshe_app/utils/dialog_util.dart';
import 'package:huajianshe_app/utils/toast_utils.dart';
import 'package:huajianshe_app/widget/AvatarWidget.dart';
import 'package:huajianshe_app/widget/BadgeWidget.dart';
import 'package:huajianshe_app/widget/RoundedCornerWidget.dart';
import 'package:huajianshe_app/widget/SimpleScrollView.dart';
import 'package:huajianshe_app/widget/SmartButton.dart';
import 'package:huajianshe_app/widget/appbar/CAppBar.dart';
import 'package:huajianshe_app/widget/dialog/SelectMediaBottomSheet.dart';
import 'package:image_picker/image_picker.dart';

//圈子设置
class CircleEditPage extends StatefulWidget {

  final int? circleId;

  const CircleEditPage(this.circleId, {Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _CircleEditPageState();
  }
}

class _CircleEditPageState extends BaseState<CircleEditPage> {

  CircleCreateInfo? data;

  MediaFileInfo? cover;
  MediaFileInfo? bg;
  final _picker = ImagePicker();
  TextEditingController nameController = TextEditingController();
  TextEditingController priceController = TextEditingController();
  TextEditingController platformController = TextEditingController();
  TextEditingController inviterController = TextEditingController();
  TextEditingController introController = TextEditingController();
  
  @override
  void initState() {
    super.initState();
    sendReq(Api.circleEditInfo(), CircleEditResp(), data: {'id': widget.circleId}, doNotShowProgressBar: false);
  }

  @override
  void onReqSuccess<T>(T t, int code, String msg, String path) {
    if (t is CircleEditResp) {
      data = t.data;
      String background = data?.background ?? '';
      if (background.split(',').length > 1) {
        background = background.split(',')[0];
      }
      String bgId = data?.bgId ?? '';
      if (bgId.split(',').length > 1) {
        bgId = bgId.split(',')[0];
      }
      bg = MediaFileInfo(background, false, int.parse(bgId));
      cover = MediaFileInfo(data?.cover ?? '', false, data?.coverId);
      nameController.text = data?.title ?? '';
      priceController.text = data?.price ?? '';
      platformController.text = ((data?.platform ?? 0) * 100).toString();
      inviterController.text = ((data?.inviter ?? 0) * 100).toString();
      introController.text = data?.desc ?? '';
      setState(() => {});
    } else if (t is UploadResp) {
      print('${t.data?.url}');
      if (t.data?.url != null) {
        if (chooseType == 1) cover = MediaFileInfo(t.data!.url!, false, t.data!.id);
        else if (chooseType == 2) bg = MediaFileInfo(t.data!.url!, false, t.data!.id);
        setState(() => {});
      }
    } else if (t is BaseResp) {
      if (t.code == 0) {
        // data = CircleCreateInfo();
        // setState(() => null);
        AppNavigator.pop(context);
      }
      Toast.show(t.msg);
    }
  }

  @override
  Widget build(BuildContext context) {
    return
      Scaffold(
        appBar: CAppBar(title: '圈子设置', backImgUrl: 'ic_black_arrow', overlayStyle: SystemUiOverlayStyle.dark),
        backgroundColor: C.grayF6,
        body: SimpleScrollView(
          padding: EdgeInsets.only(top: 10, left: 13, right: 13, bottom: 13),
          children: [
            RoundedCornerWidget(backgroundColor: Colors.white, width: double.infinity, height: 200, radius: 13,
                child: Column(children: [
                  Padding(padding: EdgeInsets.all(15),
                      child: InkWell(onTap: () => { chooseCover() }, child: Row(children: [
                        Text('圈子头像', style: TS(15, C.gray1A),),
                        Spacer(),
                        AvatarWidget(cover?.path, 40, 0, 0),
                        W(10),
                        LoadImage('ic_gray_right_arrow')
                      ]))
                  ),
                  H(10),
                  Row(crossAxisAlignment: CrossAxisAlignment.end, children: [
                    W(15),
                    Text('圈子背景', style: TS(15, C.gray1A),),
                    W(8),
                    Text('尺寸说明:16*9', style: TS(12, C.gray999),)
                  ],),
                  H(6),
                  InkWell(onTap: () { chooseBg(); },
                      child: Row(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [
                        W(15),
                        if (bg != null) BadgeWidget(width: 77, height: 77, widget: LoadImage(bg?.path, width: 70, height: 70),
                          badget: GestureDetector(onTap: () {
                            setState(() { bg = null; });
                          }, child: LoadImage('ic_delete_media')),
                        ),
                        Spacer(),
                        Padding(padding: EdgeInsets.only(top: 35), child: LoadImage('ic_gray_right_arrow')),
                        W(15),
                      ])
                  )
                ])
            ),
            H(10),
            RoundedCornerWidget(backgroundColor: Colors.white, width: double.infinity, height: 50, radius: 13,
                child: Row(children: [
                  W(15),
                  Text('圈子名称', style: TS(15, C.gray1A),),
                  Expanded(child: TextField(autofocus: false, controller: nameController, focusNode: null,
                      style: TS(14, C.gray1A), maxLength: 8, textDirection: TextDirection.rtl, decoration: new InputDecoration(
                        border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none,
                        counterText: '', hintText: "最多8字", hintStyle: TS(14, C.grayC3), hintTextDirection: TextDirection.rtl,)
                  )),
                  W(15),
                ])
            ),
            H(10),
            RoundedCornerWidget(backgroundColor: Colors.white, width: double.infinity, height: 50, radius: 13,
                child: Row(children: [
                  W(15),
                  Text('圈子价格', style: TS(15, C.gray1A),),
                  Expanded(child: TextField(autofocus: false, controller: priceController, focusNode: null, keyboardType: TextInputType.number,
                      style: TS(14, C.gray1A), maxLength: 12, textDirection: TextDirection.rtl, decoration: new InputDecoration(
                        border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none,
                        counterText: '', hintText: "请设置圈子价格", hintStyle: TS(14, C.grayC3), hintTextDirection: TextDirection.rtl,)
                  )),
                  W(15),
                ])
            ),
            H(10),
            RoundedCornerWidget(backgroundColor: Colors.white, width: double.infinity, height: 50, radius: 13,
                child: Row(children: [
                  W(15),
                  Text('添加圈子标签', style: TS(15, C.gray1A),),
                  Spacer(),
                  Text('请输入圈子标签(最多3个)', style: TS(14, C.grayC3),),
                  W(15),
                  LoadImage('ic_gray_right_arrow'),
                  W(15),
                ])
            ),
            H(10),
            RoundedCornerWidget(backgroundColor: Colors.white, width: double.infinity, height: 50, radius: 13,
                child: Row(children: [
                  W(15),
                  Text('平台抽成', style: TS(15, C.gray1A),),
                  Expanded(child: TextField(autofocus: false, controller: platformController, focusNode: null, keyboardType: TextInputType.number,
                      style: TS(14, C.gray1A), maxLength: 12, textDirection: TextDirection.rtl, decoration: new InputDecoration(
                        border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none,
                        counterText: '', hintText: "(0-100)", hintStyle: TS(14, C.grayC3), hintTextDirection: TextDirection.rtl,)
                  )),
                  Text('%', style: TS(15, C.gray1A),),
                  W(15),
                ])
            ),
            H(10),
            RoundedCornerWidget(backgroundColor: Colors.white, width: double.infinity, height: 50, radius: 13,
                child: Row(children: [
                  W(15),
                  Text('邀请分成', style: TS(15, C.gray1A),),
                  Expanded(child: TextField(autofocus: false, controller: inviterController, focusNode: null, keyboardType: TextInputType.number,
                      style: TS(14, C.gray1A), maxLength: 12, textDirection: TextDirection.rtl, decoration: new InputDecoration(
                        border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none,
                        counterText: '', hintText: "(0-100)", hintStyle: TS(14, C.grayC3), hintTextDirection: TextDirection.rtl,)
                  )),
                  Text('%', style: TS(15, C.gray1A),),
                  W(15),
                ])
            ),
            H(10),
            RoundedCornerWidget(backgroundColor: Colors.white, width: double.infinity, height: null, radius: 13,
                child: Column(children: [
                  H(15),
                  Row(children: [
                    W(15),
                    Text('圈子介绍', style: TS(15, C.gray1A),),
                  ]),
                  H(15),
                  Padding(padding: EdgeInsets.symmetric(horizontal: 15), child:
                  TextField(autofocus: false, controller: introController, focusNode: null,
                    maxLines: 5, maxLength: 100,
                    decoration: InputDecoration(
                      isDense: true,
                      contentPadding: EdgeInsets.only(left: 12, right: 12, top: 10, bottom: 10),
                      fillColor: C.grayF6,
                      filled: true,
                      border: new OutlineInputBorder(
                        borderSide: BorderSide.none,
                        borderRadius: const BorderRadius.all(Radius.circular(9.0)),
                      ),
                      hintStyle: TS(14, C.grayC3),
                      hintText: "请输入圈子简介, 吸引更多感兴趣的人加入~",
                    ),
                  )
                  ),
                  H(10),
                ])
            ),
          ],
          bottomView: SmartButton(width: double.infinity, height: 50, text: '提交发布', textColor: Colors.white,
            fontSize: 17, onPressed: submit,),
        ),
      );
  }

  int chooseType = 1; //1表示头像2表示背景

  chooseCover() {
    chooseType = 1;
    showMediaDialog();
  }

  chooseBg() {
    chooseType = 2;
    showMediaDialog();
  }

  void showMediaDialog() {
    DialogUtil.showBottomDialogV2(context, SelectMediaBottomSheet(
      includeVideo: false,
      onMediaResult: (isVideo, isCamera) {
        onMediaResult(isVideo, isCamera);
      },
    ), radius: 13, margin: EdgeInsets.symmetric(horizontal: 5));
  }

  void onMediaResult(bool isVideo, isCamera) async {
    var source = isCamera ? ImageSource.camera : ImageSource.gallery;
    final pickedFile = await _picker.getImage(source: source);
    if (pickedFile != null) {
      File file = File(pickedFile.path);
      uploadImage(file);
    }
  }

  uploadImage(File image) async {
    final String path = image.path;
    final String filename = path.substring(path.lastIndexOf('/') + 1);
    var file = await MultipartFile.fromFile(path, filename: filename);
    debugPrint('file:${file.filename.toString()}');
    sendReq(Api.uploadPic(), UploadResp(), data: {'file': file});
  }

  submit() {
    data?.coverId = cover?.id; //todo
    if (data?.coverId == null) {
      Toast.show('请上传圈子头像');
      return;
    }
    data?.bgId = bg?.id?.toString(); //todo
    if (data?.bgId == null) {
      Toast.show('请上传圈子背景');
      return;
    }
    data?.title = nameController.text;
    if (data?.title?.isEmpty == true) {
      Toast.show('请输入圈子名称');
      return;
    }
    data?.desc = introController.text;
    data?.labels = '1'; //todo
    data?.price = priceController.text;
    if (platformController.text.isEmpty) {
      data?.platform = 0;
    } else {
      double platformRatio = double.parse(platformController.text);
      if (platformRatio > 100 || platformRatio < 0) {
        Toast.show('请输入正确的抽成比例(1-100)');
        return;
      }
      data?.platform = platformRatio / 100;
    }
    if (inviterController.text.isEmpty) {
      data?.inviter = 0;
    } else {
      double inviterRatio = double.parse(inviterController.text);
      if (inviterRatio > 100 || inviterRatio < 0) {
        Toast.show('请输入正确的分成比例(1-100)');
        return;
      }
      data?.inviter = inviterRatio / 100;
    }
    sendReq(Api.circleEdit(), BaseResp(), data: data?.toJson(), doNotShowProgressBar: false);
  }
}